package com.example.teaching_server.controller;

import com.example.teaching_server.common.ApiResponse;
import com.example.teaching_server.dto.TermDTO;
import com.example.teaching_server.service.TermService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/terms")
@RequiredArgsConstructor
@Tag(name = "学期管理", description = "学期信息查询接口")
public class TermController {
    private final TermService termService;

    /**
     * 获取当前学期
     */
    @GetMapping("/current")
    @Operation(summary = "获取当前学期", description = "获取当前活跃的学期信息")
    public ApiResponse<TermDTO> getCurrentTerm() {
        log.info("开始获取当前学期");

        try {
            TermDTO currentTerm = termService.getCurrentTerm();
            log.info("成功获取当前学期: {}", currentTerm.getTermName());
            return ApiResponse.success("当前学期获取成功", currentTerm);
        } catch (Exception e) {
            log.error("获取当前学期失败", e);
            return ApiResponse.fail("获取当前学期失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有学期
     */
    @GetMapping
    @Operation(summary = "获取学期列表", description = "获取所有学期信息列表")
    public ApiResponse<List<TermDTO>> getAllTerms() {
        log.info("开始获取学期列表");

        try {
            List<TermDTO> terms = termService.getAllTerms();
            log.info("成功获取{}个学期", terms.size());
            return ApiResponse.success("学期列表获取成功", terms);
        } catch (Exception e) {
            log.error("获取学期列表失败", e);
            return ApiResponse.fail("获取学期列表失败: " + e.getMessage());
        }
    }

    /**
     * 按日期查询学期
     */
    @GetMapping("/by-date")
    @Operation(summary = "按日期查询学期", description = "根据指定日期查询相关的学期信息")
    public ApiResponse<List<TermDTO>> getTermsByDate(
            @Parameter(description = "查询日期，格式：yyyy-MM-dd")
            @RequestParam String date) {

        log.info("开始按日期查询学期: date={}", date);

        try {
            List<TermDTO> terms = termService.getTermsByDate(LocalDate.parse(date));
            log.info("成功查询到{}个相关学期", terms.size());
            return ApiResponse.success("学期查询成功", terms);
        } catch (Exception e) {
            log.error("按日期查询学期失败: date={}", date, e);
            return ApiResponse.fail("学期查询失败: " + e.getMessage());
        }
    }
}
